package com.wjy.game.setting;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import lombok.Data;

/**
 * @author wjy
 * @date 2025/5/20 16:42
 * @description 服务器设置
 */
@Data
@Component
public class ServerSetting {

    @Value("${server.setting}")
    private String settingPath;

    private transient Properties properties;

    private String ip;

    private int port;

    public void load() {
        if (properties == null) {
            properties = new Properties();
            try (FileInputStream is = new FileInputStream(settingPath)) {
                properties.load(is);
                ip = properties.getProperty("ip");
                port = Integer.parseInt(properties.getProperty("port"));
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void save() {
        properties.setProperty("ip", ip);
        properties.setProperty("port", String.valueOf(port));
        try (FileOutputStream os = new FileOutputStream(settingPath)) {
            properties.store(os, "");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
